# _*_ coding: UTF-8 _*_
# @Time     : 2021/2/25 下午 01:37
# @Author   : Li Jie
# @Site     : http://www.hzdledu.com/
# @File     : prac2_client1.py
# @Software : PyCharm

import socket
import select
import threading


class Client:
    def __init__(self, host, port):
        self.host = '127.0.0.1'
        self.port = 8888
        self.addr = (host, port)
        self.start_client()
        self.start_threads()

    def start_client(self):
        print('初始化客户端...')
        self.client_socket = socket.socket()
        self.client_socket.connect(self.addr)
        print(f'客户端连接到服务器{self.addr}')

    def start_threads(self):
        print('初始化客户端接收和发送线程...')
        self.thread_recv = threading.Thread(target=self.recv_data, name='client_recv_thread')
        self.thread_send = threading.Thread(target=self.send_data, name='client_send_thread')
        self.thread_recv.start()
        self.thread_send.start()
        self.thread_recv.join()
        self.thread_send.join()

    def recv_data(self):
        while True:
            # rs, ws, es = select.select([self.client_socket], [], [])
            # if self.client_socket in rs:
            #     try:
            #         data = self.client_socket.recv(1024).decode()
            #         print(data)
            #     except Exception as e:
            #         print(e)
            #         exit()
            try:
                data = self.client_socket.recv(1024).decode()
                print(data)
            except Exception as e:
                print(e)
                exit()

    def send_data(self):
        while True:
            try:
                data = input('>>>')
            except Exception:
                print('无法输入')
                exit()
            try:
                self.client_socket.send(data.encode())
            except Exception as e:
                print(e)
                exit()


if __name__ == '__main__':
    client = Client('127.0.0.1', 8888)
